﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using myTutor.Models;
using System.Web.Helpers;

namespace myTutor.Controllers
{
    public partial class HomeController : Controller
    {
        public ActionResult SearchId(string keySearch)
        {
            keySearch = keySearch ?? "";
            int idSearch = 0;
            var model = new List<SearchModel>();

            try
            {
                idSearch = int.Parse(keySearch.Remove(0, 1));
            }
            catch
            {
                keySearch = null;
            }

            if (!string.IsNullOrEmpty(keySearch))
            {
                if (keySearch.StartsWith("L"))
                {
                    ViewBag.Type = "class";
                    ViewBag.MoreInfoTitle = "Yêu cầu";
                    ViewBag.ActionName = "GetClass";
                    ViewBag.ControllerName = "Tutor";
                    ViewBag.DetailControllerName = "Class";
                    model = Db.db.Classes.Where(i => i.IsDeleted != true && i.Status == "3" && i.Id == idSearch).OrderByDescending(i => i.UpdatedTime).Select(i => new SearchModel { Id = i.Id, Class = i.ClassRequirement.PupilClassId, Subjects = i.ClassRequirement.Subjects, Address = i.DistrictMaster.Name + ", " + i.ProvinceMaster.Name, Salary = i.ClassRequirement.SalaryAmount, MoreInfo = i.ClassRequirement.TutorGender }).ToList();
                }
                else if (keySearch.StartsWith("G"))
                {
                    ViewBag.Type = "tutor";
                    ViewBag.MoreInfoTitle = "Thành phần";
                    ViewBag.ActionName = "HireTutor";
                    ViewBag.ControllerName = "Class";
                    ViewBag.DetailControllerName = "Tutor";
                    model = Db.db.TutorClassFindingRequests.Where(i => i.IsDeleted != true && i.Status == "3" && i.Id == idSearch).OrderByDescending(i => i.UpdatedTime).Select(i => new SearchModel { Id = i.Id, Class = i.TutorClassRequireSkill.CanTeachClassLevelFromId, Subjects = i.TutorClassRequireSkill.Subjects, Address = i.DistrictMaster.Name + ", " + i.ProvinceMaster.Name, Salary = i.TutorClassRequireSkill.SalaryAmount, MoreInfo = i.Gender + "|" + i.TutorLevel }).ToList();
                }
            }

            return View("Search", model);
        }

        [HttpPost]
        public ActionResult SearchId()
        {
            try
            {
                string keySearch = Request.Form["keySearch"].ToUpper();
                return RedirectToAction("SearchId", new { keySearch = keySearch });
            }
            catch 
            {
                return View("Search");
            }
        }

        public ActionResult Search()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Search(List<SearchModel> model)
        {
            string searchType = Request.Form["searchType"];
            if (string.IsNullOrEmpty(searchType))
            {
                ModelState.AddModelError("searchType", "Chưa chọn Loại Tìm Kiếm.");
                return View();
            }
            var classHasMinId = Db.db.TutorClassFindingRequests.OrderBy(i => i.Id).FirstOrDefault();
            int? searchDomain = -1;
            var provinceHasMinId = Db.db.ProvinceMasters.OrderBy(i => i.Id).FirstOrDefault();
            int? searchProvinceFrom = provinceHasMinId != null ? provinceHasMinId.Id : -1;
            int? searchProvinceTo = -1;
            var districtHasMinId = Db.db.DistrictMasters.OrderBy(i => i.Id).FirstOrDefault();
            int? searchDistrictFrom = districtHasMinId != null ? districtHasMinId.Id : -1;
            int? searchDistrictTo = -1;
            var minSalaryAmount = Db.db.SalaryMasters.OrderBy(i => i.Id).FirstOrDefault();
            int? minSalary = minSalaryAmount != null ? minSalaryAmount.Amount : -1;
            var maxSalaryAmount = Db.db.SalaryMasters.OrderByDescending(i => i.Id).FirstOrDefault();
            int? maxSalary = maxSalaryAmount != null ? maxSalaryAmount.Amount : -1;

            try
            {
                searchDomain = int.Parse(Request.Form["searchDomain"]);
            }
            catch { }

            try
            {
                searchProvinceFrom = int.Parse(Request.Form["searchProvince"]);
                searchProvinceTo = searchProvinceFrom;
            }
            catch
            {
                var provinceHasMaxId = Db.db.ProvinceMasters.OrderByDescending(i => i.Id).FirstOrDefault();
                searchProvinceTo = provinceHasMaxId != null ? provinceHasMaxId.Id : -1;
            }

            try
            {
                searchDistrictFrom = int.Parse(Request.Form["searchDistrict"]);
                searchDistrictTo = searchDistrictFrom;
            }
            catch
            {
                var districtHasMaxId = Db.db.DistrictMasters.OrderByDescending(i => i.Id).FirstOrDefault();
                searchDistrictTo = districtHasMaxId != null ? districtHasMaxId.Id : -1;
            }

            try
            {
                minSalary = SalaryMaster.GetSalaryMasterById(int.Parse(Request.Form["minSalary"])).Amount;
            }
            catch { }

            try
            {
                maxSalary = SalaryMaster.GetSalaryMasterById(int.Parse(Request.Form["maxSalary"])).Amount;
            }
            catch { }

            if (minSalary > maxSalary)
            {
                int? temp = minSalary;
                minSalary = maxSalary;
                maxSalary = temp;
            }

            ViewBag.Type = "tutor";
            ViewBag.MoreInfoTitle = "Thành phần";
            ViewBag.ActionName = "HireTutor";
            ViewBag.ControllerName = "Class";
            ViewBag.IdName = "tutorId";
            ViewBag.DetailControllerName = "Tutor";

            switch (searchType)
            {
                case "0":
                    if (searchDomain != -1)
                    {
                        model = Db.db.TutorClassFindingRequests.Where(i => i.IsDeleted != true && i.Status == "3" && i.TutorClassRequireSkill.CanTeachClassLevelFromId == searchDomain && i.ProvinceId >= searchProvinceFrom && i.ProvinceId <= searchProvinceTo && i.DistrictId >= searchDistrictFrom && i.DistrictId <= searchDistrictTo && i.TutorClassRequireSkill.SalaryAmount >= minSalary && i.TutorClassRequireSkill.SalaryAmount <= maxSalary).OrderByDescending(i => i.UpdatedTime).Select(i => new SearchModel { Id = i.Id, Class = i.TutorClassRequireSkill.CanTeachClassLevelFromId, Subjects = i.TutorClassRequireSkill.Subjects, Address = i.DistrictMaster.Name + ", " + i.ProvinceMaster.Name, Salary = i.TutorClassRequireSkill.SalaryAmount, MoreInfo = i.Gender + "|" + i.TutorLevel }).ToList();
                    }
                    else
                    {
                        model = Db.db.TutorClassFindingRequests.Where(i => i.IsDeleted != true && i.Status == "3" && i.ProvinceId >= searchProvinceFrom && i.ProvinceId <= searchProvinceTo && i.DistrictId >= searchDistrictFrom && i.DistrictId <= searchDistrictTo && i.TutorClassRequireSkill.SalaryAmount >= minSalary && i.TutorClassRequireSkill.SalaryAmount <= maxSalary).OrderByDescending(i => i.UpdatedTime).Select(i => new SearchModel { Id = i.Id, Class = i.TutorClassRequireSkill.CanTeachClassLevelFromId, Subjects = i.TutorClassRequireSkill.Subjects, Address = i.DistrictMaster.Name + ", " + i.ProvinceMaster.Name, Salary = i.TutorClassRequireSkill.SalaryAmount, MoreInfo = i.Gender + "|" + i.TutorLevel }).ToList();
                    }
                    break;
                case "1":
                    if (searchDomain != -1)
                    {
                        model = Db.db.TutorClassFindingRequests.Where(i => i.IsDeleted != true && i.Status == "3" && i.TutorLevel == "1" && i.TutorClassRequireSkill.CanTeachClassLevelFromId == searchDomain && i.ProvinceId >= searchProvinceFrom && i.ProvinceId <= searchProvinceTo && i.DistrictId >= searchDistrictFrom && i.DistrictId <= searchDistrictTo && i.TutorClassRequireSkill.SalaryAmount >= minSalary && i.TutorClassRequireSkill.SalaryAmount <= maxSalary).OrderByDescending(i => i.UpdatedTime).Select(i => new SearchModel { Id = i.Id, Class = i.TutorClassRequireSkill.CanTeachClassLevelFromId, Subjects = i.TutorClassRequireSkill.Subjects, Address = i.DistrictMaster.Name + ", " + i.ProvinceMaster.Name, Salary = i.TutorClassRequireSkill.SalaryAmount, MoreInfo = i.Gender + "|" + i.TutorLevel }).ToList();
                    }
                    else
                    {
                        model = Db.db.TutorClassFindingRequests.Where(i => i.IsDeleted != true && i.Status == "3" && i.TutorLevel == "1" && i.ProvinceId >= searchProvinceFrom && i.ProvinceId <= searchProvinceTo && i.DistrictId >= searchDistrictFrom && i.DistrictId <= searchDistrictTo && i.TutorClassRequireSkill.SalaryAmount >= minSalary && i.TutorClassRequireSkill.SalaryAmount <= maxSalary).OrderByDescending(i => i.UpdatedTime).Select(i => new SearchModel { Id = i.Id, Class = i.TutorClassRequireSkill.CanTeachClassLevelFromId, Subjects = i.TutorClassRequireSkill.Subjects, Address = i.DistrictMaster.Name + ", " + i.ProvinceMaster.Name, Salary = i.TutorClassRequireSkill.SalaryAmount, MoreInfo = i.Gender + "|" + i.TutorLevel }).ToList();
                    }
                    break;
                case "2":
                    if (searchDomain != -1)
                    {
                        model = Db.db.TutorClassFindingRequests.Where(i => i.IsDeleted != true && i.Status == "3" && i.TutorLevel == "2" && i.TutorClassRequireSkill.CanTeachClassLevelFromId == searchDomain && i.ProvinceId >= searchProvinceFrom && i.ProvinceId <= searchProvinceTo && i.DistrictId >= searchDistrictFrom && i.DistrictId <= searchDistrictTo && i.TutorClassRequireSkill.SalaryAmount >= minSalary && i.TutorClassRequireSkill.SalaryAmount <= maxSalary).OrderByDescending(i => i.UpdatedTime).Select(i => new SearchModel { Id = i.Id, Class = i.TutorClassRequireSkill.CanTeachClassLevelFromId, Subjects = i.TutorClassRequireSkill.Subjects, Address = i.DistrictMaster.Name + ", " + i.ProvinceMaster.Name, Salary = i.TutorClassRequireSkill.SalaryAmount, MoreInfo = i.Gender + "|" + i.TutorLevel }).ToList();
                    }
                    else
                    {
                        model = Db.db.TutorClassFindingRequests.Where(i => i.IsDeleted != true && i.Status == "3" && i.TutorLevel == "2" && i.ProvinceId >= searchProvinceFrom && i.ProvinceId <= searchProvinceTo && i.DistrictId >= searchDistrictFrom && i.DistrictId <= searchDistrictTo && i.TutorClassRequireSkill.SalaryAmount >= minSalary && i.TutorClassRequireSkill.SalaryAmount <= maxSalary).OrderByDescending(i => i.UpdatedTime).Select(i => new SearchModel { Id = i.Id, Class = i.TutorClassRequireSkill.CanTeachClassLevelFromId, Subjects = i.TutorClassRequireSkill.Subjects, Address = i.DistrictMaster.Name + ", " + i.ProvinceMaster.Name, Salary = i.TutorClassRequireSkill.SalaryAmount, MoreInfo = i.Gender + "|" + i.TutorLevel }).ToList();
                    }
                    break;
                case "3":
                    if (searchDomain != -1)
                    {
                        model = Db.db.TutorClassFindingRequests.Where(i => i.IsDeleted != true && i.Status == "3" && i.TutorLevel == "3" && i.TutorClassRequireSkill.CanTeachClassLevelFromId == searchDomain && i.ProvinceId >= searchProvinceFrom && i.ProvinceId <= searchProvinceTo && i.DistrictId >= searchDistrictFrom && i.DistrictId <= searchDistrictTo && i.TutorClassRequireSkill.SalaryAmount >= minSalary && i.TutorClassRequireSkill.SalaryAmount <= maxSalary).OrderByDescending(i => i.UpdatedTime).Select(i => new SearchModel { Id = i.Id, Class = i.TutorClassRequireSkill.CanTeachClassLevelFromId, Subjects = i.TutorClassRequireSkill.Subjects, Address = i.DistrictMaster.Name + ", " + i.ProvinceMaster.Name, Salary = i.TutorClassRequireSkill.SalaryAmount, MoreInfo = i.Gender + "|" + i.TutorLevel }).ToList();
                    }
                    else
                    {
                        model = Db.db.TutorClassFindingRequests.Where(i => i.IsDeleted != true && i.Status == "3" && i.TutorLevel == "3" && i.ProvinceId >= searchProvinceFrom && i.ProvinceId <= searchProvinceTo && i.DistrictId >= searchDistrictFrom && i.DistrictId <= searchDistrictTo && i.TutorClassRequireSkill.SalaryAmount >= minSalary && i.TutorClassRequireSkill.SalaryAmount <= maxSalary).OrderByDescending(i => i.UpdatedTime).Select(i => new SearchModel { Id = i.Id, Class = i.TutorClassRequireSkill.CanTeachClassLevelFromId, Subjects = i.TutorClassRequireSkill.Subjects, Address = i.DistrictMaster.Name + ", " + i.ProvinceMaster.Name, Salary = i.TutorClassRequireSkill.SalaryAmount, MoreInfo = i.Gender + "|" + i.TutorLevel }).ToList();
                    }
                    break;
                case "4":
                    if (searchDomain != -1)
                    {
                        model = Db.db.Classes.Where(i => i.IsDeleted != true && i.Status == "3" && i.ClassRequirement.PupilClassId == searchDomain && i.ProvinceId >= searchProvinceFrom && i.ProvinceId <= searchProvinceTo && i.DistrictId >= searchDistrictFrom && i.DistrictId <= searchDistrictTo && i.ClassRequirement.SalaryAmount >= minSalary && i.ClassRequirement.SalaryAmount <= maxSalary).OrderByDescending(i => i.UpdatedTime).Select(i => new SearchModel { Id = i.Id, Class = i.ClassRequirement.PupilClassId, Subjects = i.ClassRequirement.Subjects, Address = i.DistrictMaster.Name + ", " + i.ProvinceMaster.Name, Salary = i.ClassRequirement.SalaryAmount, MoreInfo = i.ClassRequirement.TutorGender }).ToList();
                    }
                    else
                    {
                        model = Db.db.Classes.Where(i => i.IsDeleted != true && i.Status == "3" && i.ProvinceId >= searchProvinceFrom && i.ProvinceId <= searchProvinceTo && i.DistrictId >= searchDistrictFrom && i.DistrictId <= searchDistrictTo && i.ClassRequirement.SalaryAmount >= minSalary && i.ClassRequirement.SalaryAmount <= maxSalary).OrderByDescending(i => i.UpdatedTime).Select(i => new SearchModel { Id = i.Id, Class = i.ClassRequirement.PupilClassId, Subjects = i.ClassRequirement.Subjects, Address = i.DistrictMaster.Name + ", " + i.ProvinceMaster.Name, Salary = i.ClassRequirement.SalaryAmount, MoreInfo = i.ClassRequirement.TutorGender }).ToList();
                    }
                    ViewBag.Type = "class";
                    ViewBag.MoreInfoTitle = "Yêu cầu";
                    ViewBag.ActionName = "GetClass";
                    ViewBag.ControllerName = "Tutor";
                    ViewBag.IdName = "classId";
                    ViewBag.DetailControllerName = "Class";
                    break;
                default: model = new List<SearchModel>();
                    break;
            }

            return View(model);
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        public ActionResult Contact()
        {
            if (Request.IsAuthenticated)
            {
                ContactModel model = new ContactModel();
                UserMaster user = UserMaster.GetUserByUserName(User.Identity.Name);
                model.FullName = user.FirstName + " " + user.LastName;
                model.Email = user.Email;
                model.Phone = user.UserProfile == null ? "" : user.UserProfile.MobiPhone;
                return View(model);
            }
            return View();
        }

        [HttpPost]
        public ActionResult Contact(ContactModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    Config.SetupWebmail();
                    WebMail.Send(
                        to: model.Email,
                        subject: "Ghi nhận phản hồi",
                        body: "Xin chào: <strong>" + model.FullName + "</strong>." + (string.IsNullOrEmpty(model.Phone) ? "" : (" Điện thoại: " + model.Phone)) + "<br />"
                        + "Cảm ơn bạn đã liên hệ! Chúng tôi sẽ phản hồi lại đến bạn trong thời gian sớm nhất. Một lần nữa, chúng tôi xin chân thành cảm ơn!<br/ >"
                        + "<strong>Nội dung bạn đã gởi</strong>: <i>\"" + model.Content + "\"</i>"
                    );
                    WebMail.Send(
                        to: Config.GetSmtpServerTo(),
                        subject: model.Title,
                        body: "Ý kiến góp ý từ: <strong>" + model.FullName + "</strong><br /><ul><li>E-mail: " + model.Email + "</li><li>Điện thoại: " + model.Phone + "</li><br />"
                        + "<i>\"" + model.Content + "\"</i>"
                    );
                    return RedirectToAction("Info", "Shared", new { title = "Cảm ơn", message = "Cảm ơn bạn đã liên hệ! Chúng tôi sẽ phản hồi lại đến bạn trong thời gian sớm nhất. Một lần nữa, chúng tôi xin chân thành cảm ơn!", returnPage = "Trang chủ", returnUrl = "/" });
                }
                catch
                {
                    ModelState.AddModelError("", "Rất tiếc, có sự cố trong quá trình gởi thông tin, vui lòng thử lại sau!");
                }
            }
            return View(model);
        }
    }
}
